import requests
from .log_utils import logger


def get_login_token(config):
    """获取登录 token"""
    if not isinstance(config, dict):
        logger.error("配置参数不是有效的字典格式。")
        return None
    # 获取当前激活的环境配置
    active_env = config.get("active_env")
    env_config = config.get("environments", {}).get(active_env, {})
    host = env_config.get("host")

    if not host:
        logger.error(f"未找到环境 {active_env} 的host配置")
        return None
    if not host:
        logger.error("配置中缺少主机地址。")
        return None
    login_config = config.get("login", {})
    uuid_url = f"{host}{login_config.get('uuid_path')}"
    login_url = f"{host}{login_config.get('login_path')}"
    if not uuid_url or not login_url:
        logger.error("配置中缺少 UUID 或登录路径。")
        return None

    headers = {"Content-Type": "application/json"}

    def fetch_uuid():
        try:
            response = requests.get(uuid_url, headers=headers)
            response.raise_for_status()
            return response.json()
        except requests.RequestException as e:
            logger.error(f"请求 UUID 失败：{e}")
            return None

    def perform_login(uuid):
        login_data = {
            "username": login_config.get("username"),
            "password": login_config.get("password"),
            "code": login_config.get("code"),
            "uuid": uuid,
        }
        try:
            response = requests.post(login_url, headers=headers, json=login_data)
            response.raise_for_status()
            return response.json()
        except requests.RequestException as e:
            logger.error(f"登录请求失败：{e}")
            return None

    uuid_data = fetch_uuid()
    if not uuid_data or not isinstance(uuid_data, dict):
        logger.error("未获取到有效的 UUID 或 UUID 响应不是有效的字典格式。")
        return None

    uuid = uuid_data.get("uuid")
    if not uuid:
        logger.error("未获取到有效的 UUID。")
        return None

    login_response = perform_login(uuid)
    if not login_response:
        return None

    token = login_response.get("token")
    return token if token else None
